package com.logic.modular.game.building.mapper;


import com.logic.comment.util.RedisUtils;
import com.logic.config.netty.web.service.MessageService;
import com.logic.modular.game.building.domain.PvpCityBuildings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.logic.modular.game.GameConstant.PVP_MATCH_CITY_BUILDING_key1;
import static com.logic.modular.game.GameConstant.PVP_MATCH_CITY_BUILDING_key2;

@Slf4j
@Service
public class PvpCityBuildMapper {
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private HashOperations<String, String, PvpCityBuildings> hashOperations;

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public Map<String, PvpCityBuildings> mapCache(
            @NotNull(message = "matchId不能为空") Long matchId
    ) {
        String key1 = String.format(PVP_MATCH_CITY_BUILDING_key1, matchId);
        redisUtils.expire(key1, 60, TimeUnit.MINUTES);
        return hashOperations.entries(key1);
    }

    public PvpCityBuildings selectCache(Long playerId, Long currentMatchId, Long targetCityId, Integer no) {
        return mapCache(currentMatchId).get(String.format(PVP_MATCH_CITY_BUILDING_key2, playerId, targetCityId, no));
    }

    public List<PvpCityBuildings> listCache(
            @NotNull(message = "matchId不能为空") Long matchId
    ) {
        return new ArrayList<>(mapCache(matchId).values());
    }

    public void saveCache(
            PvpCityBuildings pvpCityBuildings
    ) {
        String key1 = String.format(PVP_MATCH_CITY_BUILDING_key1,
                pvpCityBuildings.getMatchId()
        );
        String key2 = String.format(PVP_MATCH_CITY_BUILDING_key2,
                pvpCityBuildings.getPlayerId(), pvpCityBuildings.getCoreCityId(), pvpCityBuildings.getNo()
        );
        redisUtils.hPut(key1, key2, pvpCityBuildings);
        Long playerId = pvpCityBuildings.getPlayerId();
        MessageService.sendMessageToUser(playerId, MessageService.updateJsonObject("pvpCityBuildings", pvpCityBuildings));
    }
}
